//
//  MNDBaofuBindCardViewController.m
//  minidai
//
//  Created by Steven.Yung on 2017/6/8.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDBaofuBindCardViewController.h"
#import "MNDBaofuBankListViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "MNDCustomFooterView.h"
#import "NSString+JKNormalRegex.h"
#import "MNDBaofuBankListModel.h"
#import "MNDWebViewController.h"

@interface MNDBaofuBindCardViewController ()

@property (weak, nonatomic) IBOutlet UILabel *userRealNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *bankNameLabel;
@property (weak, nonatomic) IBOutlet UIImageView *bankLogo;
@property (weak, nonatomic) IBOutlet UITextField *bankcardTextField;
@property (strong, nonatomic) MNDCustomFooterView *footerView;
@property (strong, nonatomic) MNDBaofuBankListModel *selectedBank;

@property(nonatomic, copy) NSString *bankCard;

@property (nonatomic) CGFloat rowHeight;

@end

@implementation MNDBaofuBindCardViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.rowHeight = 50.0;
    
    self.footerView = [[MNDCustomFooterView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - self.rowHeight * 3 - 64 - 35)];
    self.tableView.tableFooterView = self.footerView;
    [self.footerView.footerButton addTarget:self action:@selector(bindCardAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self initialLeftBarButtons];
    
    if (self.bankModel) {
        
        [self configContent];
    } else {
        [self loadBankInfo];
    }
    WeakSelf(self);
    [self.bankcardTextField.rac_textSignal subscribeNext:^(NSString *text) {
        if (text.length > 19 ) {
            weakself.bankcardTextField.text = [text substringToIndex:19];
        }
    }];
//    RAC(self, bankCard) = self.bankcardTextField.rac_textSignal;
//    
//    RAC(self.bankcardTextField, enabled) = [RACSignal combineLatest:@[RACObserve(self, bankCard)] reduce:^id(NSString *cardnember){
//        return @(cardnember.length <= 19);
//    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)initialLeftBarButtons {
    UIImage *backImage = [UIImage imageNamed:@"navi_back_btn_black"];
    
    //创建返回按钮
    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage
                                                                          style:UIBarButtonItemStylePlain
                                                                         target:self
                                                                         action:@selector(backAction:)];
    //设置返回按钮的颜色
    [backBarButtonItem setTintColor:kColorBackButtonColor];
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    //将两个BarButtonItem都返回给NavigationItem
    if (@available(iOS 11.0, *)) {
        self.navigationItem.leftBarButtonItem = backBarButtonItem;
    } else {
        self.navigationItem.leftBarButtonItems = @[spaceItem, backBarButtonItem];
    }
    
}

- (void)backAction:(id)sender {
    [self dismissViewControllerAnimated:YES completion:^{
        if (self.bindCardResultBlock) {
            self.bindCardResultBlock(NO);
        }
    }];
    
}

#pragma mark - Network

- (void)loadBankInfo {
    WeakSelf(self);
    
    [NetworkProgressHUD showHud];
    
    [APIManager sendRequestWithPath:API_GET_BANK_ACCOUNT parameters:[MNDSign signedParam] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            weakself.bankModel = [MNDBankModel mj_objectWithKeyValues:responseModel.data];
            [weakself configContent];
            
        } else {
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
                
            } else {
                [NetworkProgressHUD showHudMsg:@"获取数据失败"];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)configContent {
    self.userRealNameLabel.text = self.bankModel.userAmount.userRealname;
}

- (void)bindCard {
    
    WeakSelf(self);
    [NetworkProgressHUD showHud];
    
    NSDictionary *params = [MNDSign signedParamWithDict:@{@"bank_card_number": self.bankcardTextField.text,
                                                          @"vc_bank_name_id" : self.selectedBank.vc_bank_name_id}];
    [APIManager sendRequestWithPath:API_BAOFU_ADD_BANKCARD parameters:params method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD showHudMsg:@"添加银行卡成功"];
            
            [weakself dismiss];
            
        } else {
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
                
            } else {
                [NetworkProgressHUD showHudMsg:@"添加银行卡失败，请重试"];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)dismiss {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self dismissViewControllerAnimated:YES completion:^{
            
            if (self.bindCardResultBlock) {
                self.bindCardResultBlock(YES);
            }
        }];
    });
}

#pragma mark - Action

- (void)bindCardAction:(UIButton *)sender {
    if (!self.selectedBank || self.selectedBank.vc_bank_name.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请选择银行"];
        return;
    }
    
    if (self.bankcardTextField.text.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请输入银行卡号"];
        return;
    }
    
//    if (!self.bankcardTextField.text.jk_bankCardluhmCheck) {
//        [NetworkProgressHUD showHudMsg:@"您输入的银行卡号不正确"];
//        return;
//    }
    
    [self bindCard];
}


- (IBAction)readQuotaAction:(id)sender {
    //传YES表示是限额说明
    [self performSegueWithIdentifier:[MNDBaofuBankListViewController description] sender:@YES];
}

- (IBAction)selectBankAction:(id)sender {
    [self performSegueWithIdentifier:[MNDBaofuBankListViewController description] sender:nil];
}

#pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:[MNDBaofuBankListViewController description]]) {
        
        WeakSelf(self);
        
        MNDBaofuBankListViewController *bankListVC = segue.destinationViewController;
        if (sender && [sender boolValue]) {
            bankListVC.isQuota = [sender boolValue];
            bankListVC.title = @"限额说明";
        }
        bankListVC.bankSelectedBlock = ^(MNDBaofuBankListModel *bank) {
            weakself.selectedBank = bank;
            [weakself configBank];
        };
    }
}

- (void)configBank {
    self.bankNameLabel.text = self.selectedBank.vc_bank_name;
//    self.bankLogo.image = [UIImage imageNamed:@"bank_logo_placeholder"];
    [self.bankLogo setHidden:NO];
    [self.bankLogo sd_setImageWithURL:[NSURL URLWithString:self.selectedBank.vc_bank_img] placeholderImage:[UIImage imageNamed:@"bank_logo_placeholder"]];
}


#pragma mark - Table view data source

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.rowHeight;
}
//
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//#warning Incomplete implementation, return the number of sections
//    return 0;
//}
//
//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//#warning Incomplete implementation, return the number of rows
//    return 0;
//}

/*
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];
    
    // Configure the cell...
    
    return cell;
}
*/

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


@end
